/*
 * Copyright (C) 2009 Jakub Miara
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.araim.rringtone;

import java.util.ArrayList;
import java.util.Random;

import com.araim.rringtone.db.RandomRingtoneDatabase;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

/**
 * 
 * @author Jakub Miara
 * @version 1.0
 * 
 *          This is the class that performs the actual change of a ringtone.
 *          It's subscribed for broadcasts of change phone state. When the phone
 *          becomes IDLE it randomly chooses the ringtone and sets it as a
 *          current, default one.
 * 
 *          This operation is also performed when user makes the call (the
 *          outgoing call) while this is unnecessary, it doesn't affect the
 *          randomness.
 * 
 */
public class RingtoneChanger extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		String state = bundle.getString("state");

		// @TODO: detect if this is IDLE after an incoming call, or after an
		// outgoing one

		// if the state has changed to IDLE
		if (state != null && state.equals("IDLE")) {
			Log.d(RandomRingtone.TAG,"IDLE state change received");
			// get the shared preferences for this application
			SharedPreferences settings = context.getSharedPreferences(
					RandomRingtone.RRINGTONE_PREFS_NAME, 0);
			// check if random ringtone is active
			boolean active = settings.getBoolean(
					RandomRingtone.RRINGTONE_ACTIVE, false);
			Log.d(RandomRingtone.TAG,"Random ringtone is " +(active?"on":"off"));
			// if it is...
			if (active) {

				RingtoneManager rm = new RingtoneManager(context);
				Random rr = new Random();

				RandomRingtoneDatabase rdb = new RandomRingtoneDatabase(context);
				ArrayList<RingtoneInfo> rings = rdb.getAllRingtones();

				try {
					Log.d(RandomRingtone.TAG,"Found " + rings.size() + " user selected ringtones ");
					// do nothing if no ringtone has been selected
					if (rings.size() == 0) {
						return;
					}
					int num = -1;
					do {
						// get a random index
						num = rr.nextInt(rings.size());

						RingtoneInfo ri = rings.get(num);

						// create an uri for the randomly selected ringtone (the
						// URI consists of the URI stored in DB + the id of a
						// ringtone)
						Uri uri = Uri.parse(ri.getUri() + "/" + ri.getId());
						// if this ringtone exists (it might have been removed)
						if (rm.getRingtonePosition(uri) != -1) {
							RingtoneManager
									.setActualDefaultRingtoneUri(context,
											RingtoneManager.TYPE_RINGTONE, uri);
							Log.i(RandomRingtone.TAG,"Ringtone \"" + ri.getName() + "\" has been set");
							return;
						} else {
							Log.i(RandomRingtone.TAG,"Ringtone \""+ri.getName() +"\" is no longer valid");
							// the ringtone is no longer valid - remove it
							rings.remove(num);
							rdb.delete(ri.getId());
							// if there are no more - don't set
							if (rings.size() == 0) {
								Log.i(RandomRingtone.TAG,"After removing invalid ringtones there is not one left");
								return;
							}
						}
					} while (true);
				} catch (Exception e) {
					Log.e(RandomRingtone.TAG, "Error setting ringtone: " + e.toString());
				}
			}
		}
	}
}
